<template>
  <div class="page-refund-order-info">
    <div class="new-page-title">
      <div class="line" />
      <div class="text">
        {{ $t('refundOrderDetail.returnDetails') }}
      </div>
    </div>
    <div
      v-if="platInterveneSts===1"
      class="plat-intervene"
    >
      <el-icon :size="14">
        <WarningFilled />
      </el-icon>
      <span v-if="stillAveTime">用户申请平台介入售后，请在{{ dataForm.platformProcessingEndTime }}前处理</span>
      <span v-else>当前商家、用户正在举证，请在{{ dataForm.interventionEndTime }}后进行结果介入判定</span>
    </div>
    <el-form
      label-width="auto"
      @submit.prevent
      @keyup.enter="onSubmit()"
    >
      <div class="mod-order-refundOrderInfo">
        <div class="refundId">
          <span class="title">{{ $t('order.refundId') }}</span>
          <span class="text">{{ dataForm.refundSn }}</span>
        </div>
        <div class="content">
          <div class="order-number">
            <div class="num-cont">
              <div class="state-title">
                <div class="item">
                  <div class="title">
                    {{ $t('refundOrderDetail.returnType') }}：
                  </div>
                  <div class="text">
                    <div v-if="dataForm.refundType === 1">
                      {{ $t("refundOrderDetail.fullRefund") }}
                    </div>
                    <div v-if="dataForm.refundType === 2">
                      {{ $t("refundOrderDetail.sigGoosRefund") }}
                    </div>
                  </div>
                </div>
                <p />
                <div class="item">
                  <div class="title">
                    {{ $t('refundOrderDetail.returnMethod') }}：
                  </div>
                  <div class="text">
                    <div v-if="dataForm.applyType === 1">
                      {{ $t("order.onlyRefund") }}
                    </div>
                    <div v-if="dataForm.applyType === 2">
                      {{ $t("order.refundAndMoney") }}
                    </div>
                  </div>
                </div>
              </div>
              <div class="refund-progress">
                <refund-steps
                  ref="refundStepsRef"
                  :refund-detail="dataForm"
                />
              </div>
            </div>
          </div>
          <div class="order-state">
            <div class="state-cont">
              <div class="order-info">
                <div class="order-details refund-record-left">
                  <div class="detail-title">
                    <span class="prompt">{{ $t("refundOrderDetail.returnDetails") }}</span>
                  </div>
                  <div class="detail-cont">
                    <div class="detail01">
                      <div class="text-width">
                        <div class="text-width-item">
                          <span class="title">{{ $t('order.number') }}：</span>
                          <span class="text">{{ dataForm.orderNumber }}</span>
                        </div>
                        <div class="text-width-item">
                          <span class="title">{{ $t('order.actualAmount') }}：</span>
                          <span class="text">{{ moneyFormat(dataForm.orderAmount) }}</span>
                        </div>
                        <div class="text-width-item">
                          <span class="title">{{ $t('order.refundAmount') }}：</span>
                          <span class="text">{{ moneyFormat(dataForm.refundAmount) + $t("transport.yuan") + "+ " + dataForm.refundScore + $t("order.score") }}</span>
                        </div>
                        <div class="text-width-item">
                          <span class="title">{{ $t('order.applicationTime') }}：</span>
                          <span class="text">{{ dataForm.applyTime }}</span>
                        </div>
                        <div class="text-width-item">
                          <span class="title">{{ $t('refundOrderDetail.refundReason') }}：</span>
                          <span class="text">{{ dataForm.buyerReason }}</span>
                        </div>
                        <div class="text-width-item">
                          <span class="title">{{ $t('refundOrderDetail.refundInstructions') }}：</span>
                          <span class="text">{{ dataForm.buyerDesc }}</span>
                        </div>
                        <div class="text-width-item">
                          <span class="title">{{ $t('refundOrderDetail.returnVoucher') }}：</span>
                          <div v-if="refundProofList?.length">
                            <imgGeneral :img-list="refundProofList" />
                          </div>
                          <div v-else>
                            无
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <!-- 退款记录 -->
                <div class="buyers">
                  <div class="refund-record-title detail-title">
                    <span>退款记录</span>
                  </div>
                  <div class="refund-record">
                    <refundRecord :refund-detail="dataForm" />
                  </div>
                </div>
                <!-- / 退款记录 -->
              </div>
              <div
                v-if="dataForm.applyType === 2 && dataForm.refundDelivery && (dataForm.refundDelivery.deyNu || dataForm.refundDelivery.imgs)"
                class="order-info"
              >
                <div class="order-details">
                  <div class="detail-title">
                    <span class="prompt">{{ $t("refundOrderDetail.logisticsDetails") }}</span>
                  </div>
                  <div class="detail-cont">
                    <div class="detail01">
                      <div class="text-width">
                        <div
                          v-if="dataForm.refundDelivery && dataForm.refundDelivery.deyName"
                          class="text-width-item"
                        >
                          <span class="title">{{ $t('refundOrderDetail.logisticsName') }}：</span>
                          <span class="text">{{ dataForm.refundDelivery.deyName }}</span>
                        </div>
                        <div
                          v-if="dataForm.refundDelivery && dataForm.refundDelivery.deyNu"
                          class="text-width-item"
                        >
                          <span class="title">{{ $t('order.trackingNumber') }}：</span>
                          <span class="text">{{ dataForm.refundDelivery.deyNu }}</span>
                        </div>
                        <div
                          v-if="dataForm.refundDelivery && dataForm.refundDelivery.senderRemarks"
                          class="text-width-item"
                        >
                          <span class="title">{{ $t('order.compradorMsg') }}：</span>
                          <span class="text">{{ dataForm.refundDelivery.senderRemarks }}</span>
                        </div>
                        <div
                          v-if="dataForm.refundDelivery && dataForm.refundDelivery.senderMobile"
                          class="text-width-item"
                        >
                          <span class="title">{{ $t('order.buyerPhone') }}：</span>
                          <span>{{ dataForm.refundDelivery.senderMobile }}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="detail-title">
                    <!-- 物流凭证 -->
                    <span>{{ $t('refundOrderDetail.Logisticsvoucher') }}</span>
                  </div>
                  <div class="buyers-info">
                    <div class="detail02">
                      <imgs-upload
                        v-model="refundDeliveryPhotos"
                        :disabled="true"
                        :modal="false"
                        :prompt="false"
                      />
                    </div>
                  </div>
                </div>
                <div class="buyers">
                  <div
                    v-if="deliveryDto"
                    class="detail-title"
                  >
                    <!-- 退款物流信息 -->
                    <span>{{ $t('order.logisticsStatus') }}：</span>
                    <span
                      v-if="deliveryDto.state === 0"
                      class="l-state"
                    >{{ $t("order.noRecord") }}</span>
                    <span
                      v-if="deliveryDto.state === 1"
                      class="l-state"
                    >{{ $t("order.collected") }}</span>
                    <span
                      v-if="deliveryDto.state === 2"
                      class="l-state"
                    >{{ $t("order.delivering") }}</span>
                    <span
                      v-if="deliveryDto.state === 3"
                      class="l-state"
                    >{{ $t("order.haveBeenReceived") }}</span>
                    <span
                      v-if="deliveryDto.state === 4"
                      class="l-state"
                    >{{ $t("order.problemPiece") }}</span>
                    <span
                      v-if="deliveryDto.state === 201"
                      class="l-state"
                    >{{ $t("order.reachTheDestinationCity") }}</span>
                  </div>
                  <div
                    v-if="deliveryDto"
                    class="logistics-box"
                  >
                    <!-- 退款时间 -->
                    <div
                      v-if="dataForm.returnMoneySts === 5 && dataForm.refundTime !== null"
                      class="item"
                    >
                      <div class="time">
                        {{ dataForm.refundTime }}
                      </div>
                      <div class="text">
                        {{ $t("refund.refundMoney") }}
                      </div>
                    </div>
                    <!-- 收货时间 -->
                    <div
                      v-if="dataForm.returnMoneySts === 5 && dataForm.receiveTime !== null"
                      class="item"
                    >
                      <div class="time">
                        {{ dataForm.receiveTime }}
                      </div>
                      <div class="text">
                        {{ $t("refund.receivedGoods") }}
                      </div>
                    </div>
                    <div
                      v-for="(trace, index) in deliveryDto.traces"
                      :key="index"
                      class="item"
                    >
                      <div class="time">
                        {{ trace.acceptTime }}
                      </div>
                      <div class="text">
                        {{ trace.acceptStation }}
                      </div>
                    </div>
                    <div
                      v-if="deliveryDto.traces &&deliveryDto.traces.length < 1"
                      class="item"
                    >
                      {{ $t("order.noLogisticsInformation") }}
                    </div>
                    <!-- 发货时间 -->
                    <div
                      v-if="dataForm.returnMoneySts >= 3 && dataForm.shipTime !== null"
                      class="item"
                    >
                      <div class="time">
                        {{ dataForm.shipTime }}
                      </div>
                      <div class="text">
                        {{ $t("refund.buyerHasShipped") }}
                      </div>
                    </div>
                    <!-- 同意退款时间 -->
                    <div
                      v-if="dataForm.returnMoneySts >= 2 && dataForm.decisionTime !== null"
                      class="item"
                    >
                      <div class="time">
                        {{ dataForm.decisionTime }}
                      </div>
                      <div class="text">
                        {{ $t("refund.merchantHasAgree") }}
                      </div>
                    </div>
                    <!-- 申请时间 -->
                    <div
                      v-if="dataForm.returnMoneySts >= 1"
                      :class="['item', dataForm.returnMoneySts >= 1?'left-line':'']"
                    >
                      <div class="time">
                        {{ dataForm.applyTime }}
                      </div>
                      <div class="text">
                        {{ $t("refund.buyerApply") }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="item-list">
                <el-table
                  :data="prodList"
                  header-cell-class-name="table-header"
                  row-class-name="table-row-row"
                  :row-style="{ height:'82px'}"
                >
                  <el-table-column
                    :label="$t('refundOrderDetail.refundItems')"
                    width="400"
                  >
                    <template #default="scope">
                      <div class="prod-info">
                        <prod-pic
                          :pic="scope.row.pic"
                          width="60px"
                          height="60px"
                        />
                        <div class="con">
                          <span
                            v-if="scope.row.giveawayOrderItemId"
                            class="gift-icon"
                          >{{ $t("order.giveawayPord") }}</span>
                          <div
                            class="prod-info-text"
                            :class="{'gift-prod-text': scope.row.giveawayOrderItemId}"
                          >
                            {{ scope.row.prodName }}
                          </div>
                          <div
                            v-if="scope.row.skuName"
                            class="prod-info-sku"
                          >
                            {{ scope.row.skuName }}
                          </div>
                        </div>
                      </div>
                      <!-- 赠品 -->
                      <div
                        v-if="dataForm.orderItems.length > 1"
                        class="gift-prod table-cell-text"
                      >
                        <div
                          v-for="(item,index) in scope.row.giveawayList"
                          :key="index"
                          class="item"
                        >
                          <div class="name prod-info-text">
                            {{ '【' + $t("order.giveawayPord") + '】' }}{{ item.prodName }}
                          </div>
                          <span class="num">{{ item.skuName }} ×{{ item.prodCount }}</span>
                        </div>
                      </div>
                      <!-- / 赠品 -->
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="price"
                    :label="$t('order.unitPrice')"
                  >
                    <template #default="scope">
                      <span v-if="!scope.row.giveawayOrderItemId">{{ moneyFormat(scope.row.price) }}</span>
                      <span v-if="scope.row.giveawayOrderItemId">￥{{ getUnitPrice(scope.row.giveawayAmount, scope.row.prodCount) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="count"
                    :label="$t('order.quantity')"
                  >
                    <template #default="scope">
                      <span>{{ scope.row.prodCount }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="productTotalAmount"
                    :label="$t('order.prodTotalPrice')"
                  >
                    <template #default="scope">
                      <span v-if="dataForm.refundType === 1 && !scope.row.giveawayOrderItemId">{{ moneyFormat(scope.row.productTotalAmount) }}</span>
                      <span v-if="dataForm.refundType === 2 && !scope.row.giveawayOrderItemId">{{ moneyFormat(bigProductTotalAmount(scope.row.price, dataForm.goodsNum)) }}</span>
                      <span v-if="scope.row.giveawayOrderItemId">{{ moneyFormat(scope.row.giveawayAmount) }}</span>
                    </template>
                  </el-table-column>

                  <el-table-column
                    prop="actualTotal"
                    :label="$t('order.actualAmount')"
                  >
                    <template #default="scope">
                      <span v-if="dataForm.refundType === 1 && !scope.row.giveawayOrderItemId">{{ moneyFormat(scope.row.actualTotal) }}</span>
                      <span v-if="dataForm.refundType === 2 && !scope.row.giveawayOrderItemId">{{ moneyFormat(bigActualTotal(scope.row.actualTotal, scope.row.prodCount)) }}</span>
                      <span v-if="scope.row.giveawayOrderItemId">-</span>
                      <el-tag
                        v-if="scope.row.shareReduce > 0"
                        type="danger"
                        effect="dark"
                      >
                        {{ $t("marketing.discount") }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-if="dataForm.refundType === 2"
                    prop="productTotalAmount"
                    :label="$t('order.returnAmount')"
                    width="180"
                  >
                    <template #default="scope">
                      <span v-if="!scope.row.giveawayOrderItemId">{{ dataForm.refundAmount + $t("transport.yuan") + " + " + dataForm.refundScore + $t("order.score") }}</span>
                      <span
                        v-if="scope.row.giveawayOrderItemId"
                        class=""
                      >-</span>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <template v-if="platInterveneSts===1">
                <div class="sellerRemark">
                  <div class="remark-title star">
                    申请审批：
                  </div>
                  <div class="remark-content">
                    <el-radio-group
                      v-model="auditForm.isAgreeRefund"
                      @change="refundAuditChange"
                    >
                      <el-radio
                        :label="1"
                      >
                        商家承担退款
                      </el-radio>
                      <el-radio
                        :label="3"
                      >
                        不同意
                      </el-radio>
                    </el-radio-group>
                  </div>
                </div>
                <div class="sellerRemark">
                  <div class="remark-title">
                    <span class="refundAmount-title">退款金额</span>
                    <el-tooltip
                      effect="dark"
                      content="享受平台优惠的订单不能修改退款金额"
                      placement="top"
                    >
                      <el-icon><QuestionFilled /></el-icon>
                    </el-tooltip>
                    ：
                  </div>
                  <div
                    v-if="!dataForm.platformAmount"
                    class="remark-content"
                  >
                    <div class="refund-price">
                      <el-input
                        v-model="auditForm.refundPrice"
                        type="number"
                        placeholder="请输入"
                        :disabled="auditForm.isAgreeRefund===3"
                        style="width: 250px;outline-style: none;"
                        @blur="onRefundPriceBlur"
                        @keydown="channelInputLimit"
                      />
                      <span class="unit">元</span>
                    </div>
                    <span class="pri-tips">平台售后可按需修改退款金额</span>
                  </div>
                  <!-- 使用了平台优惠（会员折扣、平台优惠券、积分抵扣）的订单，平台介入时，不能修改退款金额 -->
                  <div
                    v-else
                    class="refund-amount-score"
                  >
                    <span
                      v-if="dataForm.refundAmount"
                      class="text"
                    >
                      {{ moneyFormat(dataForm.refundAmount) }}{{ $t("transport.yuan") }}
                    </span>
                    <span
                      v-if="dataForm.refundAmount && dataForm.refundScore"
                      class="text"
                    >
                      +
                    </span>
                    <span
                      v-if="dataForm.refundScore"
                      class="text"
                    >
                      {{ dataForm.refundScore }}{{ $t("order.score") }}
                    </span>
                  </div>
                </div>
                <div class="sellerRemark">
                  <div class="remark-title star">
                    平台留言：
                  </div>
                  <div class="remark-content">
                    <el-input
                      v-model="auditForm.platMsg"
                      type="textarea"
                      style="width: 100%;outline-style: none;"
                      :rows="5"
                      maxlength="250"
                      show-word-limit
                    />
                  </div>
                </div>
                <div class="btn-bar">
                  <el-button
                    type="primary"
                    @click="onHandleAudit()"
                  >
                    {{ $t("order.confirmTreatment") }}
                  </el-button>
                </div>
              </template>

              <!-- 自营 -->
              <!-- returnMoneySts ['', '买家申请', '卖家接受', '买家发货', '卖家收货', '退款成功']  -->
              <template v-if="isSelf">
                <div
                  v-if="dataForm.returnMoneySts === 1"
                  class="sellerRemark"
                >
                  <div class="remark-title">
                    {{ $t("order.applyForApproval") }}：
                  </div>
                  <div class="remark-content">
                    <el-radio-group v-model="selfForm.isAgreeRefund">
                      <el-radio :label="2">
                        {{ dataForm.applyType === 1 ? $t("order.agreeToRefundA") : $t("order.agree") }}
                      </el-radio>
                      <el-radio :label="3">
                        {{ $t("order.disagree") }}
                      </el-radio>
                    </el-radio-group>
                  </div>
                </div>

                <!-- 退货退款 returnMoneySts -1 退款关闭 -->
                <div
                  v-if="dataForm.applyType === 2 && selfForm.isAgreeRefund === 2 && dataForm.returnMoneySts !== -1"
                  class="sellerRemark"
                >
                  <div
                    v-if="dataForm.refundDelivery"
                    class="remark-title"
                  >
                    {{ $t("publics.deliveryAddr") }}：
                  </div>
                  <!-- 买家申请阶段 -->
                  <div
                    v-if="dataForm.returnMoneySts === 1"
                  >
                    <el-select
                      v-model="selfForm.refundAddrId"
                      style="width: 350px"
                      :placeholder="$t('tip.select')"
                      @change="$forceUpdate()"
                    >
                      <el-option
                        v-for="item in addrList"
                        :key="item.refundAddrId"
                        :label="item.receiverName+'，'+item.receiverMobile+'，'+item.province + item.city + item.area + item.addr"
                        :value="item.refundAddrId"
                      />
                    </el-select>
                    <!--新建/刷新-->
                    <!-- <div
                      class="default-btn text-btn"
                      @click="refreshChange"
                    >
                      刷新
                    </div>
                    <el-divider direction="vertical" />
                    <div
                      class="default-btn text-btn"
                      @click.stop="onAddOrUpdate()"
                    >
                      新建
                    </div> -->
                  </div>
                  <div
                    v-if="dataForm.refundDelivery.receiverAddr"
                    class="remark-content"
                    style="line-height: 32px;"
                  >
                    {{ dataForm.refundDelivery.receiverName + '，' + dataForm.refundDelivery.receiverMobile + '，' + dataForm.refundDelivery.receiverAddr }}
                  </div>
                </div>

                <!-- 退货状态 -->
                <div
                  v-if="dataForm.shipTime &&!dataForm.cancelTime &&!dataForm.rejectTime"
                  class="sellerRemark"
                >
                  <div class="remark-title">
                    退货状态：
                  </div>
                  <div class="remark-content">
                    <el-radio-group
                      v-model="selfForm.isReceiver"
                      :disabled="dataForm.returnMoneySts !== 3"
                    >
                      <el-radio :label="1">
                        已收货
                      </el-radio>
                      <el-radio :label="0">
                        未收货
                      </el-radio>
                    </el-radio-group>
                  </div>
                </div>

                <!-- 退货申请 -->
                <div
                  v-if="dataForm.shipTime &&!dataForm.cancelTime &&!dataForm.rejectTime"
                  class="sellerRemark"
                >
                  <div class="remark-title">
                    退货申请：
                  </div>
                  <div class="remark-content">
                    <el-radio-group
                      v-model="selfForm.isAgreeRefund"
                      :disabled="dataForm.returnMoneySts !== 3"
                    >
                      <el-radio :label="2">
                        {{ $t("order.agreeToRefundA") }}
                      </el-radio>
                      <el-radio :label="3">
                        拒绝退款
                      </el-radio>
                    </el-radio-group>
                  </div>
                </div>

                <!-- 不同意 拒绝原因 -->
                <div
                  v-if="selfForm.isAgreeRefund === 3"
                  class="sellerRemark"
                >
                  <div class="remark-title denial">
                    拒绝原因：
                  </div>
                  <el-input
                    v-model="selfForm.rejectMessage"
                    type="textarea"
                    style="width: 100%;outline-style: none;"
                    :rows="6"
                    maxlength="250"
                    show-word-limit
                  />
                </div>
                <!-- 不同意 凭证 -->
                <div
                  v-if="selfForm.isAgreeRefund === 3"
                  class="sellerRemark"
                >
                  <div class="remark-title denial">
                    上传凭证：
                  </div>
                  <uploadProof
                    ref="uploadProofRef"
                    v-model="selfForm.voucherImgs"
                    :limit="3"
                  />
                </div>

                <!-- 商家备注 -->
                <div
                  v-if="dataForm.returnMoneySts === 1 && selfForm.isAgreeRefund === 2"
                  class="sellerRemark"
                >
                  <div class="remark-title">
                    商家备注：
                  </div>
                  <el-input
                    v-model="selfForm.sellerMsg"
                    type="textarea"
                    style="width: 100%;outline-style: none;"
                    maxlength="250"
                    show-word-limit
                  />
                </div>

                <div class="btn-bar">
                  <!-- 仅退款的时候进行的处理操作 -->
                  <div
                    v-if="dataForm.returnMoneySts === 1"
                    class="default-btn primary-btn"
                    @click="checkHandel()"
                  >
                    {{ $t("order.confirmTreatment") }}
                  </div>
                  <!-- 退货退款的时候进行的处理操作 -->
                  <div
                    v-if="dataForm.returnMoneySts === 3"
                    class="default-btn primary-btn"
                    @click="returnMoneyHandle()"
                  >
                    {{ $t("order.confirmTreatment") }}
                  </div>
                  <!-- 自营 线下  -->
                  <!-- <div
                    v-if="isOffLinePay && canFinish()"
                    class="default-btn primary-btn"
                    @click="returnMoneyComplete()"
                  >
                    退款已发放
                  </div> -->
                </div>
              </template>
            </div>
          </div>
        </div>
      </div>
    </el-form>

    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @refresh-data-list="getRefundAddrList"
    />
  </div>
</template>

<script setup>
import Big from 'big.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import refundRecord from './conponents/refund-record/index.vue'
import refundSteps from './conponents/refund-steps/index.vue'
import imgGeneral from './conponents/img-general/index.vue'
import uploadProof from './conponents/upload-proof/index.vue'
import AddOrUpdate from './add-or-update.vue'

const route = useRoute()

const formatPrice = computed(() => {
  return (value) => {
    if (!value) {
      return 0.00
    }
    return Number(value).toFixed(2)
  }
})

// 是否自营
const isSelf = computed(() => {
  const { isSelf } = dataForm.value
  return isSelf == 1
})

// 是否线下支付
const isOffLinePay = computed(() => {
  const { payType } = dataForm.value
  return payType == 12
})

/**
 * 仅退款的时候，进行的退款处理操作
 * 提交处理
 */
const checkHandel = Debounce(() => {
  const { isAgreeRefund } = selfForm.value
  const { refundType, applyType, status } = dataForm.value
  if (isAgreeRefund === 2) {
    if (isUploadInvoice.value) {
      ElMessageBox.confirm('该订单已上传发票,确认退款后请查看并处理已上传发票的内容', '提示', {
        confirmButtonText: $t('resource.confirm'),
        cancelButtonText: $t('resource.cancel'),
        type: 'warning'
      }).then(() => {
        if (refundType === 2 && applyType === 1 && status === 2) {
          checkIsLastOrderItem(handelReturnMoney)
          return
        }
        handelReturnMoney()
      }).catch(() => {})
      return
    } else {
      // 部分退款 仅退款 已付款
      if (refundType === 2 && applyType === 1 && status === 2) {
        checkIsLastOrderItem(handelReturnMoney)
        return
      }
      handelReturnMoney()
    }
    return
  }
  handelReturnMoney()
})

const uploadProofRef = ref(null) // 上传凭证组件
const isProcessing = ref(false) // 是否正在处理订单
const handelReturnMoney = async () => {
  const { isAgreeRefund, rejectMessage, sellerMsg, voucherImgs } = selfForm.value
  const tempRefundAddrId = isAgreeRefund === 2 ? selfForm.value.refundAddrId : undefined
  if (isProcessing.value) {
    return
  }
  if (isAgreeRefund === 3) {
    if (!rejectMessage?.trim()) {
      ElMessage({
        message: '拒绝原因不能为空',
        type: 'error',
        duration: 1500
      })
      return
    }
    if (!voucherImgs) {
      ElMessage({
        message: '请上传凭证',
        type: 'error',
        duration: 1500
      })
      return
    }
  }
  isProcessing.value = true
  isAgreeRefund !== 3 && (selfForm.value.voucherImgs = '')
  if (isAgreeRefund === 3) {
    const saveFileRes = await uploadProofRef.value.saveAttachFileToPlat()
    if (!saveFileRes) {
      // eslint-disable-next-line require-atomic-updates
      isProcessing.value = false
      return
    }
  }
  http({
    url: http.adornUrl('/platform/orderRefund/process'),
    method: 'put',
    data: http.adornData({
      sellerMsg,
      rejectMessage,
      refundSts: isAgreeRefund,
      refundId: dataForm.value.refundId,
      refundSn: dataForm.value.refundSn,
      shopId: dataForm.value.shopId,
      refundAddrId: tempRefundAddrId,
      shopImgUrls: selfForm.value.voucherImgs // 凭证
    })
  }).then(() => {
    getRefundOrderInfo()
    isProcessing.value = false
    ElMessage({
      message: $t('publics.operation'),
      type: 'success',
      duration: 1500,
      onClose: () => {
        resetSelfForm()
      }
    })
  }).catch(() => {
    isProcessing.value = false
  })
}

/**
 * 确定退款
 */
const returnMoneyHandle = async () => {
  if (isProcessing.value) return
  const { isAgreeRefund, rejectMessage, isReceiver, voucherImgs } = selfForm.value
  if (isAgreeRefund === 3) {
    if (!rejectMessage?.trim()) {
      ElMessage({
        message: '拒绝原因不能为空',
        type: 'error',
        duration: 1500
      })
      return
    }
    if (!voucherImgs) {
      ElMessage({
        message: '请上传凭证',
        type: 'error',
        duration: 1500
      })
      return
    }
  }
  isProcessing.value = true
  isAgreeRefund !== 3 && (selfForm.value.voucherImgs = '')
  if (isAgreeRefund === 3) {
    const saveFileRes = await uploadProofRef.value.saveAttachFileToPlat()
    if (!saveFileRes) {
      // eslint-disable-next-line require-atomic-updates
      isProcessing.value = false
      return
    }
  }
  // TODO
  http({
    url: http.adornUrl('/platform/orderRefund/returnMoney'),
    method: 'put',
    data: http.adornData({
      shopId: dataForm.value.shopId,
      refundId: dataForm.value.refundId,
      refundSn: dataForm.value.refundSn,
      sellerMsg: dataForm.value.sellerMsg,
      refundSts: isAgreeRefund,
      isReceiver,
      rejectMessage,
      shopImgUrls: selfForm.value.voucherImgs // 凭证
    })
  }).then(() => {
    isProcessing.value = false
    getRefundOrderInfo()
    ElMessage({
      message: $t('publics.operation'),
      type: 'success',
      duration: 1500,
      onClose: () => {
      }
    })
  }).catch(() => {
    isProcessing.value = false
  })
}

const isUploadInvoice = ref(false)
const getIsInvoiceUpload = (orderNumber) => {
  http({
    url: http.adornUrl('/orderInvoice/is_upload'),
    method: 'get',
    params: {
      orderNumber
    }
  }).then(({ data }) => {
    isUploadInvoice.value = data
  })
}

const addrList = ref([])
const refundAddr = ref('')
/**
 * 加载收货地址模板
 */
const getRefundAddrList = (shopId) => {
  http({
    url: http.adornUrl('/platform/refundAddr/list'),
    method: 'get',
    params: http.adornParams({
      shopId
    })
  }).then(({ data }) => {
    addrList.value = data
    addrList.value?.forEach((item) => {
      if (item.defaultAddr) {
        dataForm.value.refundAddrId = item.refundAddrId
      }
    })
    if (dataForm.value.refundAddrId) {
      const index = addrList.value?.findIndex(item => item.refundAddrId === dataForm.value.refundAddrId)
      if (index || index === 0) {
        const refAddr = addrList.value[index]
        refundAddr.value = refAddr.province + refAddr.city + refAddr.area + refAddr.addr
      }
    }
  })
}

const addOrUpdateVisible = ref(false)
const addOrUpdateRef = ref(null)
// 新增
const onAddOrUpdate = (id) => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init(id, dataForm.value.shopId)
  })
}

// 刷新
const refreshChange = () => {
  getRefundAddrList(dataForm.value.shopId)
}

// 自营操作 form
const selfForm = ref({
  isAgreeRefund: 2,
  isReceiver: 1
})

const resetSelfForm = () => {
  selfForm.value = {}
}

const refundStepsRef = ref(null)
const canFinish = () => {
  const status = refundStepsRef.value.getStatus()
  if (platInterveneSts.value == -1) {
    if (dataForm.value.applyType == 1) {
      return status.onlyRefundStepsStatus == 1
    }
    if (dataForm.value.applyType == 2) {
      return status.stepsStatus == 4
    }
  }
  return false
}

// 手动发放退款
const returnMoneyComplete = () => {
  if (isProcessing.value) return
  ElMessageBox.confirm('此操作无法撤销,请确认客户已收到退款', '提示', {
    confirmButtonText: $t('resource.confirm'),
    cancelButtonText: $t('resource.cancel'),
    type: 'warning'
  }).then(() => {
    isProcessing.value = true
    http({
      url: http.adornUrl('/platform/orderRefund/process'),
      method: 'put',
      data: http.adornData({
        shopId: dataForm.value.shopId
      })
    }).then(() => {
      getRefundOrderInfo()
      isProcessing.value = false
      ElMessage({
        message: $t('publics.operation'),
        type: 'success',
        duration: 1500,
        onClose: () => {}
      })
    }).catch(() => {
      isProcessing.value = false
    })
  }).catch(() => {})
}

// 商品列表
onMounted(() => {
  dataForm.value.refundId = route.query.refundId || 0
  dataForm.value.shopId = route.query.shopId || 0
  getRefundOrderInfo()
})

onBeforeUnmount(() => {
  intervenEndTimer && clearTimeout(intervenEndTimer)
  intervenFinishTimer && clearTimeout(intervenFinishTimer)
})

const refundDeliveryPhotos = ref('')
const deliveryDto = ref(null)
const prodList = ref([])
// 平台介入状态 -1.没有介入 1.用户申请介入 2.平台同意介入 3.平台拒绝介入 5.平台同意退款成功
const platInterveneSts = ref(0)
const dataForm = ref({})
const refundProofList = ref([]) // 用户申请退款凭证
const getRefundOrderInfo = () => {
  refundDeliveryPhotos.value = ''
  if (dataForm.value.refundId) {
    http({
      url: http.adornUrl('/platform/orderRefund/info'),
      method: 'get',
      params: http.adornParams({
        refundId: dataForm.value.refundId,
        shopId: dataForm.value.shopId
      })
    }).then(({ data }) => {
      dataForm.value = data
      deliveryDto.value = dataForm.value.deliveryDto
      if (dataForm.value.refundDelivery && dataForm.value.refundDelivery.imgs) {
        refundDeliveryPhotos.value = dataForm.value.refundDelivery.imgs
      }
      // 处理商品列表
      const prods = data.orderItems
      prodList.value = prods
      if (prods && prods.length === 1 && prods[0].giveawayList && prods[0].giveawayList.length) {
        // 单个商品且有赠品时，将主商品和赠品放在同一级列表中展示
        prodList.value = [...data.orderItems, ...prods[0].giveawayList]
      }
      // 用户申请退款凭证
      refundProofList.value = onHandleImgs(data.photoFiles)

      platInterveneSts.value = data.platformInterventionStatus
      if (platInterveneSts.value === 1) {
        const nowTime = new Date().getTime() // 当前时间
        if (data.interventionEndTime) {
          const endTime = new Date(data.interventionEndTime).getTime() // 添加凭证结束时间
          endTime - nowTime > 0 && intervenEndTimeCountdown()
          if (endTime - nowTime < 0 && data.platformProcessingEndTime) {
            const finishTime = new Date(data.platformProcessingEndTime).getTime() // 平台处理介入结束时间
            finishTime - nowTime > 0 && intervenFinishTimeCountdown()
          }
        }
        // if (data.platformProcessingEndTime) {
        //   const finishTime = new Date(data.platformProcessingEndTime).getTime() // 平台处理介入结束时间
        //   finishTime - nowTime > 0 && intervenFinishTimeCountdown()
        // }
      }

      // 自营 地址 发票
      if (data.isSelf == 1) {
        getRefundAddrList(data.shopId)
        getIsInvoiceUpload(data.orderNumber)
        selfForm.value = {
          isAgreeRefund: 2,
          isReceiver: data.isReceiver ? 1 : 0
        }
      }
    })
  }
}

// 图片处理
const onHandleImgs = (imgStr) => {
  if (imgStr) {
    return imgStr.split(',')
  }
  return []
}

// 平台介入开始时间倒计时
let intervenEndTimer = null
const intervenEndTimeCountdown = () => {
  const nowTime = new Date().getTime() // 当前时间
  const endTime = new Date(dataForm.value.interventionEndTime).getTime() // 设置截止时间
  const leftTime = endTime - nowTime // 时间差

  if (leftTime >= 0) {
    // 递归每秒调用countTime方法，显示动态时间效果,
    intervenEndTimer = setTimeout(intervenEndTimeCountdown, 1000)
  } else {
    intervenEndTimer && clearTimeout(intervenEndTimer)
    intervenFinishTimer && clearTimeout(intervenFinishTimer)
    getRefundOrderInfo() // 重新获取详情
  }
}
// 平台介入结束时间倒计时
let intervenFinishTimer = null
const stillAveTime = ref(false)
const intervenFinishTimeCountdown = () => {
  const nowTime = new Date().getTime() // 当前时间
  const endTime = new Date(dataForm.value.platformProcessingEndTime).getTime() // 设置截止时间
  const leftTime = endTime - nowTime // 时间差

  if (leftTime >= 0) {
    stillAveTime.value = true
    // 递归每秒调用countTime方法，显示动态时间效果,
    intervenFinishTimer = setTimeout(intervenFinishTimeCountdown, 1000)
  } else {
    stillAveTime.value = false
    intervenFinishTimer && clearTimeout(intervenFinishTimer)
  }
}

// 审批变化
const refundAuditChange = (sts) => {
  if (sts === 3) {
    auditForm.refundPrice = ''
  }
}

// 退款金额限制
const onRefundPriceBlur = () => {
  const limitPrice = dataForm.value.maxRefundAmount || dataForm.value.refundAmount
  if (+auditForm.refundPrice < 0) {
    auditForm.refundPrice = 0
  } else if (+auditForm.refundPrice > limitPrice) {
    auditForm.refundPrice = limitPrice
  }
}

const channelInputLimit = (e) => {
  const key = e.key
  // 不允许输入'-'
  if (key === 'e' || key === '+' || key === '-') {
    e.returnValue = false
    return false
  }
  return true
}

// 提交平台介入结果
const auditForm = reactive({
  isAgreeRefund: 1,
  refundPrice: '',
  platMsg: ''
})
let isSubmit = false
const onHandleAudit = () => {
  if (!auditForm.platMsg.trim()) {
    ElMessage({
      message: '请填写留言信息',
      type: 'error',
      duration: 1500
    })
    return
  }
  if (!stillAveTime.value) {
    ElMessageBox.confirm('当前举证时间还未结束，点击确定则举证结束直接进行结果判定，是否继续操作', $t('resource.tips'), {
      confirmButtonText: $t('resource.confirm'),
      cancelButtonText: $t('resource.cancel'),
      type: 'warning'
    }).then(() => {
      if (isSubmit) return
      if (auditForm.isAgreeRefund === 3) {
        onSubmit()
        return
      }
      checkIsLastOrderItem(onSubmit)
    }).catch(() => { })
    return
  }
  if (isSubmit) return
  if (auditForm.isAgreeRefund === 3) {
    onSubmit()
    return
  }
  checkIsLastOrderItem(onSubmit)
}

const onSubmit = () => {
  const submitData = {
    refundId: dataForm.value.refundId,
    orderNumber: dataForm.value.orderNumber,
    sysType: 2, //  0.普通用户 1.商家端 2.平台端
    platformInterventionRefundType: auditForm.isAgreeRefund, // 平台介入退款方式
    refundAmount: auditForm.refundPrice || dataForm.value.refundAmount, // 平台介入退款金额
    platformMessage: auditForm.platMsg
  }
  isSubmit = true
  http({
    url: http.adornUrl('/platform/orderRefund/handlePlatformIntervention'),
    method: 'put',
    data: http.adornData(submitData)
  }).then(() => {
    ElMessage({
      message: '操作成功',
      type: 'success',
      duration: 1500,
      onClose: () => {
        isSubmit = false
        onGoBack()
      }
    })
  }).catch(() => {
    isSubmit = false
  })
}

const router = useRouter()
const onGoBack = () => {
  router.replace('/self/order-refund/index')
}

//  是否为最后一个退款项
const checkIsLastOrderItem = (fn) => {
  http({
    url: http.adornUrl('/platform/orderRefund/isLastRefund'),
    method: 'get',
    params: http.adornParams({
      refundSn: dataForm.value.refundSn
    })
  }).then(({ data }) => {
    const freightAmount = Number(dataForm.value.freightAmount)
    const isShipped = dataForm.value.dvyTime // 是否已发货
    if (data && !isShipped) {
      if (freightAmount?.toFixed(2) + '' != '0.00') {
        ElMessageBox.confirm($t('order.lastProdRefundTip').replace('[d]', freightAmount?.toFixed(2) + ' '), $t('resource.tips'), {
          confirmButtonText: $t('resource.confirm'),
          cancelButtonText: $t('resource.cancel'),
          type: 'warning'
        }).then(() => {
          fn()
        })
      } else {
        fn()
      }
    } else {
      fn()
    }
  })
}

// 精度运算-乘法
const bigProductTotalAmount = (a, b) => {
  return new Big(a).times(b)
}
// 精度运算-除法
const bigActualTotal = (a, b) => {
  if (a == null) {
    return ''
  }
  return new Big(a).div(b).times(dataForm.value.goodsNum)
}

const getUnitPrice = (value, count) => {
  if (!value) {
    return 0.00
  }
  return new Big(value).div(count).toFixed(2)
}
</script>

<style lang="scss" scoped>
@use './index.scss';
</style>
